package com.youpingou.service.impl;

import com.alibaba.fastjson.JSON;
import com.youpingou.domain.Sku;
import com.youpingou.domain.Spu;
import com.youpingou.mapper.SkuCommentMapper;
import com.youpingou.mapper.SkuMapper;
import com.youpingou.mapper.SpuMapper;
import com.youpingou.service.ESDataService;
import com.youpingou.vo.ESData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @auther Created by yuanxinqi
 */
@Service
@Transactional
public class ESDataServiceImpl implements ESDataService {

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuMapper spuMapper;



    @Autowired
    private SkuCommentMapper skuCommentMapper;

    public List<ESData> findAll(){

        ArrayList<ESData> esDataList = new ArrayList<>();
        //1. 查询数据库，获取所有的sku
        List<Sku> list = skuMapper.selectList(null);
        //2. 遍历
        for(Sku sku:list){
            //3. 准备ESData--sku
            ESData data = new ESData();
            //4. skuid
            data.setId(sku.getId());
            //5. logo
            data.setLogo(sku.getImages());
            //6. sku_name
            data.setSku_name(sku.getSkuName());

            // 查询spu
            Spu spu = spuMapper.findSpuBySpuId(sku.getSpuId());

            //7. all = sku_name + 品牌  + 三级分类
            String all = sku.getSkuName() + "  " +spu.getBrand().getBrandName()+"  " + spu.getCat3().getCatName() ;
            data.setAll(all);

            //8. on_sale_time
            Date on_sale_time = spu.getOnSaleTime();
            long time = on_sale_time.getTime();
            data.setOn_sale_time(time);

            //9. brand_id
            data.setBrand_id(spu.getBrand().getId());
            //10. cat3_id
            data.setCat3_id(spu.getCat3().getId());
            //11. 规格列表 : {"机身颜色":"白色","内存":"3GB","机身存储":"16GB"}
            Map map = JSON.parseObject(sku.getSkuIdTxt(), HashMap.class);
            data.setSpecs(map);


            //12. 价格
            data.setPrice(sku.getPrice());
            //13. spu_name
            data.setSpu_name(spu.getSpuName());
            //14. 库存量
            data.setStock(sku.getStock());
            //15. 商品详情
            data.setDescription(spu.getDescription());
            //16. 包装
            data.setPackages(spu.getPackages());
            //17. 售后
            data.setAftersale(spu.getAftersale());
            //18. 评价数
            Integer count = skuCommentMapper.findCountBySpuId(spu.getId());
            data.setComment_count(count);

            //19. 销量
            Integer sellCount = skuMapper.findSellCountBySkuId(sku.getId());
            data.setSeller_count(sellCount);

            //20. 将data放入集合
            esDataList.add(data);
        }

        //21. 返回数据
        return esDataList;
    }




}
